package com.jplus.core.plugin.async;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.jplus.core.core.ApplicationContext;
import com.jplus.core.core.beans.BeanDefinition;
import com.jplus.core.core.beans.BeanKey;
import com.jplus.core.fault.InitializationError;
import com.jplus.core.plugin.ImportSelector;
import com.jplus.core.utill.Assert;
import com.jplus.core.utill.JUtil;

public class AsyncConfigurationSelector implements ImportSelector {

	private String DEF_ASYNC = "com.jplus.core.plugin.async.AsyncConfigurationProxy";

	@Override
	public String[] selectImports(ApplicationContext context) {
		try {
			List<BeanDefinition> list = context.getBeanDefinitions().listSortBeanDefinitions();
			List<Async> ltemp = new ArrayList<>();
			for (BeanDefinition bd : list) {
				if (bd.getBeanClass().isAnnotationPresent(Async.class)) {
					// 当类上有@Async
					bd.addProxyList(new BeanKey(Class.forName(DEF_ASYNC)));
					ltemp.add(bd.getBeanClass().getAnnotation(Async.class));
					continue;
				}
				Method[] methods = bd.getBeanClass().getMethods();
				for (Method method : methods) {
					if (method.isAnnotationPresent(Async.class)){// 当方法上有@Async
						bd.addProxyList(new BeanKey(Class.forName(DEF_ASYNC)));
						ltemp.add(method.getAnnotation(Async.class));
						continue;
					}
				}
			}
			// ===============================
			for (Async as : ltemp) {
				if (JUtil.isEmpty(as.value()))
					continue;
				boolean bo = false;
				for (BeanDefinition bd : list) {
					if (bd.getBeanKey().getName().equals(as.value())) {
						bo = true;
						continue;
					}
				}
				Assert.isTrue(bo, "No qualifying bean of type [" + as.value() + "] is defined");
			}
			return new String[] { DEF_ASYNC };
		} catch (Exception e) {
			throw new InitializationError(e);
		}
	}

}
